package tpase.client.Handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import tpase.client.VO.Message;
import tpase.client.VO.PublicParam;
import tpase.client.VO.StatusCode;
import tpase.util.Util;

import java.util.Map;

@ChannelHandler.Sharable
public class ClientSetupHandler extends ChannelInboundHandlerAdapter {

    private String jpbcPath;
    private String paramPath;
    private String publicParamPath;


    public ClientSetupHandler(String paramPath) {
        this.paramPath = paramPath;
        jpbcPath = paramPath + "/a.properties";
        publicParamPath = paramPath + "/publicParam.json";
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Message request = new Message(StatusCode.PUBLIC_PARAM_REQUEST);
        ctx.writeAndFlush(request);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        Message respond = (Message) msg;
        Map<String, byte[]> map = respond.getMap();
        PublicParam publicParam = new PublicParam();
        publicParam.setMap(map);
        Util.writeJson(publicParamPath, publicParam);

        ctx.close();
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("exceptionCaught: 发生异常，关闭通道");
        System.out.println(cause.toString());
        ctx.close();
    }
}
